package com.feihong.yw189.utils.Location;

import android.Manifest;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;


/**
 * Created by Sabirjan on 2017/6/15.
 * TXGW.
 * 飞宏电子
 */

public class LocationTools implements AMapLocationListener {

    private static final String TAG = "定位LocationTools";
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    //声明mLocationOption对象
    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient = null;
    private LocationCallBack callBack;
    private Activity mContext;
    private LocationInfo locationInfo = new LocationInfo();

    public LocationTools(Activity context, LocationCallBack callBack) throws NullPointerException {

        mContext = context;
        this.callBack = callBack;
        if (mContext == null) {
            if (callBack == null) {
                throw new NullPointerException("Context is NULL");
            }
            callBack.error("Context is NULL");
            return;
        }
        checkPermission();

    }

    private void checkPermission() {

    }

    public void stopLocation() {
        try {
            if (mlocationClient != null) {
                mlocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                mlocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
                mlocationClient = null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void startLocation() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                init();

            }
        }).start();

    }

    private void init() {

        mlocationClient = new AMapLocationClient(mContext);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置返回地址信息，默认为true
        mLocationOption.setNeedAddress(true);
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        mLocationOption.setOnceLocation(true);//获取一次定位结果：
        mLocationOption.setOnceLocationLatest(true);//获取最近3s内精度最高的一次定位结果：
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();

    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                locationInfo = new LocationInfo();
                locationInfo.setAccuracy(amapLocation.getAccuracy());
                locationInfo.setAdCode(amapLocation.getAdCode());//地区编码
                locationInfo.setAddress(amapLocation.getAddress());//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                locationInfo.setCity(amapLocation.getCity());//城市信息
                locationInfo.setCityCode(amapLocation.getCityCode());//获取城市代码
                locationInfo.setCountry(amapLocation.getCountry());//国家信息
                locationInfo.setDatetime(amapLocation.getTime());
                locationInfo.setDistrict(amapLocation.getDistrict());//城区信息
                locationInfo.setLatitude(amapLocation.getLatitude());//获取纬度
                locationInfo.setLongitude(amapLocation.getLongitude());//获取精度信息
                locationInfo.setProvince(amapLocation.getProvince());//省信息
                locationInfo.setStreet(amapLocation.getStreet());//街道信息
                locationInfo.setStreetNum(amapLocation.getStreetNum());//街道门牌号信息
                mHandler.sendEmptyMessage(1);
//                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                amapLocation.getLatitude();//获取纬度
//                amapLocation.getLongitude();//获取经度
//                amapLocation.getAccuracy();//获取精度信息
//                amapLocation.getAddress();
//                amapLocation.getCountry();//国家信息
//                amapLocation.getProvince();//省信息
//                amapLocation.getCity();//城市信息
//                amapLocation.getDistrict();//城区信息
//                amapLocation.getStreet();//街道信息
//                amapLocation.getStreetNum();//街道门牌号信息
//                amapLocation.getCityCode();//城市编码
//                amapLocation.getAdCode();//地区编码

            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError-营维189", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
                String error = String.valueOf(amapLocation.getErrorCode());
                Message message = new Message();
                message.what = -1;
                message.obj = error;
                mHandler.sendMessage(message);

            }
            stopLocation();
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (callBack != null) {
                    callBack.successGetLocation(locationInfo);
                }
            } else {

                if (callBack != null) {
                    callBack.error(msg.obj.toString());
                }
            }

        }
    };


}
